package com.yonyou.crm.sys.sysinit.ctrl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.base.industry.entity.IndustryVO;
import com.yonyou.crm.base.industry.rmitf.IIndustryRmService;
import com.yonyou.crm.bpub.approval.rmitf.IProcessRmService;
import com.yonyou.crm.bpub.pctpl.entity.EnumDescription;
import com.yonyou.crm.bpub.pctpl.entity.FieldsType;
import com.yonyou.crm.bpub.pctpl.entity.FormEnumFieldDescription;
import com.yonyou.crm.bpub.pctpl.entity.FormFieldDescription;
import com.yonyou.crm.bpub.pctpl.entity.FormRefFieldDescription;
import com.yonyou.crm.bpub.pctpl.entity.FormTplDescription;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.login.context.LoginContextConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.sact.visitrule.rmitf.IVisitruleRmService;
import com.yonyou.crm.sys.org.entity.SysOrgVO;
import com.yonyou.crm.sys.org.rmitf.ISysOrgRmService;
import com.yonyou.crm.sys.tenant.entity.SysTenantVO;
import com.yonyou.crm.sys.tenant.rmitf.ISysTenantRmService;
import com.yonyou.crm.sys.user.entity.TypeEnum;
import com.yonyou.crm.sys.user.entity.UserVO;
import com.yonyou.crm.sys.user.rmitf.IUserRmService;
import com.yonyou.iuap.context.InvocationInfoProxy;

@RestController
@RequestMapping(value = "/sys/sysinit")
public class SysInitCtrl {

	@Autowired
	private ISysOrgRmService orgService;

	@Autowired
	private IUserRmService userService;
	
	@Autowired
	private ISysTenantRmService tenantService;
	
	@Autowired
	private IVisitruleRmService ruleService;
	@Autowired
	private IProcessRmService processService;
	@Autowired
	private IIndustryRmService insustryService;
	/**
	 * 修改组织
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "/org", method = RequestMethod.PUT)
	public Object update(HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {
		//根据租户ID查询组织VO，并修改组织
		SysTenantVO sysTenant = RequestUtil.getVO(request, SysTenantVO.class);
		String tenantId = InvocationInfoProxy.getTenantid();
		byte isInit=2;
		sysTenant.setIsInit(isInit);
		sysTenant.setId(Long.parseLong(tenantId));
		sysTenant = tenantService.updateSysTenant(sysTenant);
		SysOrgVO sysOrg = orgService.getDetail(sysTenant.getOrgId());
		sysOrg.setName(sysTenant.getCompanyName());
		sysOrg.setSimpleName(sysTenant.getCompanySimpleName());
		orgService.update(sysOrg);
		return ResponseUtil.getObject(sysTenant);
	}

	/**
	 * 批量保存管理员
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "/adminlist", method = RequestMethod.POST)
	public Object adminList(HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {
		//从请求中获取数据内容
		List<UserVO> userList = RequestUtil.getVOList(request, UserVO.class);	
		//处理userlist
		List<UserVO> returnList = new ArrayList<UserVO>();
		if(userList != null && userList.size() > 0){
			returnList = userService.batchUpdateAdmin(userList);
		}
		JSONObject result = new JSONObject();
		result.put("adminList", returnList);
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 初始化租户信息
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public Object tenantInfoInit(HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException{
		//在系统初始化建立了sys_org之后，sys_user表预置的user数据是否需要更新org_id
		String tenantId = InvocationInfoProxy.getTenantid();
		SysTenantVO sysTenant = tenantService.getSysTenantById(Long.parseLong(tenantId));
		IndustryVO industryVO=insustryService.getDetail(sysTenant.getCompanyIndustry(), null);
		if(industryVO!=null)
			sysTenant.setCompanyIndustryName(industryVO.getName());
		if(sysTenant.getIsInit().equals(new Byte("1"))){
			if(sysTenant.getOrgId().equals(new Long(0))){
				SysOrgVO sysOrg = new SysOrgVO();
				sysOrg.setTenantId(Long.parseLong(tenantId));
				sysOrg = orgService.insert(sysOrg);
				sysTenant.setOrgId(sysOrg.getId());
				sysTenant = tenantService.updateSysTenant(sysTenant);
				
				//生成预置拜访规则
				ruleService.savePresetedVisitrule(sysOrg.getId());
				processService.saveTenant(Long.valueOf(tenantId));
			}
			JSONObject result = new JSONObject();
			result.put("isInit", false);
			result.put("tenantInfo", sysTenant);
			return ResponseUtil.getObject(result);
		}else{
			
			Map<String, Object> paramMap = new HashMap<String, Object>();
			
			UserVO userVO = userService.detail(new Long(InvocationInfoProxy.getParameter(LoginContextConstant.UserId)));
			int userType = userVO.getType().intValue();
			//系统管理员创建集团管理员
			if (userType == TypeEnum.XTADMIN.getValue()) {
				paramMap.put("type", TypeEnum.JTADMIN.getValue());
			}
			//集团管理员创建公司管理员
			else if (userType == TypeEnum.JTADMIN.getValue()) {
				paramMap.put("type", TypeEnum.GSADMIN.getValue());
			}
			
			paramMap.put("tenantId", tenantId);
			List<UserVO> userList = userService.getAdminList(paramMap);
			JSONObject result = new JSONObject();
			result.put("isInit", true);
			result.put("tenantInfo", sysTenant);
			result.put("adminList", userList);
			return ResponseUtil.getObject(result);
		}
	}

	@RequestMapping(value = "/template/edit", method = RequestMethod.GET)
	public Object getAddTplDescription(HttpServletRequest request, HttpServletResponse response) {
		List<FormFieldDescription> columns = new ArrayList<FormFieldDescription>();
		
		FormFieldDescription orgId = new FormFieldDescription("组织","orgId",FieldsType.String,"Input",false);
		columns.add(orgId);
		
		FormFieldDescription companyName = new FormFieldDescription("企业名称","companyName",FieldsType.String,"Input",true);
		columns.add(companyName);
		
		List<EnumDescription> typeEnum = new ArrayList<EnumDescription>();
		typeEnum.add(new EnumDescription(1,"集团型企业"));
		typeEnum.add(new EnumDescription(2,"公司型企业"));
		FormEnumFieldDescription type = new FormEnumFieldDescription("企业类型","companyType",FieldsType.Enum,"Ratio","",typeEnum);
		type.setNullAble(false);
		String tenantId = InvocationInfoProxy.getTenantid();
		SysTenantVO sysTenant = tenantService.getSysTenantById(Long.parseLong(tenantId));
		if(sysTenant.getIsInit().equals(new Byte("1"))){
			type.setDisabled(false);
		}
		else
			type.setDisabled(true);
		columns.add(type);
		FormFieldDescription typeName = new FormFieldDescription("企业类型","companyTypeName",FieldsType.String,"Input",false);
		columns.add(typeName);
		
		columns.add(new FormFieldDescription("简称","companySimpleName",FieldsType.String,"Input"));
		
		FormFieldDescription companyIndustryId = new FormFieldDescription("所属行业","companyIndustry",FieldsType.String,"Input",false);
		IndustryVO industryVO=insustryService.getDetail(sysTenant.getCompanyIndustry(), null);
		if(industryVO!=null)
			sysTenant.setCompanyIndustryName(industryVO.getName());
		orgId.setDefaultValue(sysTenant.getCompanyIndustry().toString());
		columns.add(companyIndustryId);
		Map<String,String> orgMapper = new HashMap<String,String>();
		orgMapper.put("id", "companyIndustry");
		orgMapper.put("name", "companyIndustryName");
		FormFieldDescription companyIndustryName = new FormRefFieldDescription("所属行业","companyIndustryName",FieldsType.Ref,"Industry","行业",orgMapper);
		companyIndustryName.setNullAble(false);
		companyIndustryName.setDisabled(false);
		companyIndustryName.setDefaultValue(industryVO.getName());
		columns.add(companyIndustryName);
		
		FormFieldDescription companyCreatedTime = new FormFieldDescription("创立时间","companyCreatedTime",FieldsType.DateTime,"Date");
		columns.add(companyCreatedTime);
		
		columns.add(new FormFieldDescription("总部地址","companyAddress",FieldsType.String,"Input"));
		
		FormTplDescription tplDes = new FormTplDescription(columns);
		return ResponseUtil.getObject(tplDes);
	}
}
